package com.tky.conference.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePopupWindow;
import com.tky.conference.R;
import com.tky.conference.base.BaseActivity;
import com.tky.conference.base.BaseApplication;
import com.tky.conference.dao.AppointInfo;
import com.tky.conference.dao.ComeetingInfo;
import com.tky.conference.dao.DeptInfo;
import com.tky.conference.dao.HysInfo;
import com.tky.conference.dao.TreeInfo;
import com.tky.conference.entity.FailRequest;
import com.tky.conference.entity.LoginOutInfo;
import com.tky.conference.implInterfaces.AddUpdateImpl;
import com.tky.conference.interfaces.HttpResultListener;
import com.tky.conference.utlils.ShowDialog;
import com.tky.conference.utlils.ToastUtil;
import com.tky.conference.utlils.UIUtils;

import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by cll on 2015/12/21.
 */
public class MyConferenceUpdateActivity extends BaseActivity implements View.OnClickListener{
    private static  List<String> hysList = new ArrayList<>();
    private static  List<String> deptList = new ArrayList<>();
    private ComeetingInfo comeetingInfo;
    private Toolbar toolbar;
    private AddUpdateImpl addUpdateImpl;
    private LoginOutInfo loginOutInfobj;
    private ShowDialog showDialog;
    private Button commitBtn;
    private Spinner spinnerAddress,spinnerDept;
    private TextView startTime,endTime,destination,attend,record,respons;
    TimePopupWindow pwStartTime,pwEndTime;
    private String account;//全结构用户名
    private List<TreeInfo> treeInfoList;
    private List<HysInfo> hysInfoList;
    private List<DeptInfo> deptInfoList;
    private String recordId,recordName,responsId,responsName,attendId,attendName;
    private EditText subject,prepare,discribe;
    private String hysId,deptName,etime,hydd;
    private CheckBox isMessage;
    private String stime="";
    @Override
    public void initView() {
        setContentView(R.layout.activity_myupdate);
        showDialog=new ShowDialog(MyConferenceUpdateActivity.this);
        commitBtn=(Button) findViewById(R.id.bt_submit);
        spinnerAddress = (Spinner) findViewById(R.id.spinner_address);
        spinnerDept= (Spinner) findViewById(R.id.spinner_dept);
        startTime = (TextView) findViewById(R.id.tv_startTime);
        endTime = (TextView) findViewById(R.id.tv_endTime);
        destination= (TextView) findViewById(R.id.tv_destination);
        attend= (TextView) findViewById(R.id.tv_attend);
        record= (TextView) findViewById(R.id.tv_record);
        respons= (TextView) findViewById(R.id.tv_respons);
        subject= (EditText) findViewById(R.id.et_subject);
        discribe= (EditText) findViewById(R.id.et_discribe);
        prepare= (EditText) findViewById(R.id.et_prepare);
        isMessage= (CheckBox) findViewById(R.id.message);
    }

    @Override
    public void initDates() {
        comeetingInfo= (ComeetingInfo) getIntent().getSerializableExtra("ComeetInfo");
        SharedPreferences sharedPreferences=this.getSharedPreferences("save_account",MODE_PRIVATE);
        account = sharedPreferences.getString("account",null);
        subject.setText(comeetingInfo.getHyzt());
        discribe.setText(comeetingInfo.getHyms());
        //我的会议列表没有“准备工作”这个字段，所以给空字符串
        prepare.setText(" ");
        Log.i("MyConferenceUpdate", account);
        destination.setText(comeetingInfo.getHydd());
        Log.i("会议地点：", comeetingInfo.getHydd() + "hhhh" + comeetingInfo.getHyms());
        record.setText(comeetingInfo.getJlr());
        respons.setText(comeetingInfo.getFzr());
        attend.setText(comeetingInfo.getChry());
        //默认值进行初始化

        stime=comeetingInfo.getStime();//默认开始时间
        etime=comeetingInfo.getEtime();//默认结束时间
        startTime.setText(stime);
        endTime.setText(etime);
        responsName=comeetingInfo.getFzr();
        responsId=comeetingInfo.getFzrid();
        recordId=comeetingInfo.getJlrid();
        attendId=comeetingInfo.getChryid();
        recordName=comeetingInfo.getJlr();
        attendName=comeetingInfo.getChry();
        //获取树结构，部门结构以及会议室结构的id
        treeInfoList=(List<TreeInfo>) getIntent().getSerializableExtra("TREELIST");
        hysInfoList=(List<HysInfo>) getIntent().getSerializableExtra("HYSLIST");
        for(HysInfo hys:hysInfoList){
            hysList.add(hys.getPid());
        }
        deptInfoList=(List<DeptInfo>) getIntent().getSerializableExtra("DEPTLIST");
        for (DeptInfo dept:deptInfoList){
            deptList.add(dept.getName());
        }
    }

    @Override
    public void initToolBar() {
        toolbar= (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            toolbar.setTitle("修改我组织的会议 ");
        }
        setSupportActionBar(toolbar);
    }

    @Override
    public void initEvent() {
        initAddSpinner();
        initDeptSpinner();

        //时间接口的回调
        pwStartTime = new TimePopupWindow(this, TimePopupWindow.Type.ALL);
        //时间选择后的回调
        pwStartTime.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                if (getMillisTime(date) + (60 * 1000) <= System.currentTimeMillis()) {
                    Toast.makeText(BaseApplication.getContext(), "请输入合适时间", Toast.LENGTH_LONG).show();
                    startTime.setText("请点击");
                } else if (!startTime.getText().toString().equals("请点击") && !endTime.getText().toString().equals("请点击")) {
                    if (getMillisTime(endTime.getText().toString()) < getMillisTime(date)) {
                        Toast.makeText(BaseApplication.getContext(), "请输入合适时间", Toast.LENGTH_LONG).show();
                        startTime.setText(getTime(date));
                        endTime.setText("请点击");
                    } else if (getMillisTime(endTime.getText().toString()) > getMillisTime(date)) {
                        startTime.setText(getTime(date));
                    } else if (getMillisTime(endTime.getText().toString()) == getMillisTime(date)) {
                        Toast.makeText(BaseApplication.getContext(), "时间不能相同", Toast.LENGTH_LONG).show();
                        startTime.setText("请点击");
                    }
                } else {
                    startTime.setText(getTime(date));
                }
                stime=startTime.getText().toString();
            }
        });
        pwEndTime = new TimePopupWindow(this, TimePopupWindow.Type.ALL);
        //时间选择后的回调
        pwEndTime.setOnTimeSelectListener(new TimePopupWindow.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date) {
                if (startTime.getText().toString().equals("请点击")) {
                    Toast.makeText(BaseApplication.getContext(), "请输入开始时间", Toast.LENGTH_LONG).show();
                } else {
                    if (getMillisTime(startTime.getText().toString()) > getMillisTime(date)) {
                        Toast.makeText(BaseApplication.getContext(), "请输入合适时间", Toast.LENGTH_LONG).show();
                        endTime.setText("请点击");
                    } else if (startTime.getText().toString().equals(getTime(date))) {
                        Toast.makeText(BaseApplication.getContext(), "时间不能相同", Toast.LENGTH_LONG).show();
                        endTime.setText("请点击");
                    } else {
                        endTime.setText(getTime(date));
                    }
                }
                etime = endTime.getText().toString();
            }
        });
        startTime.setOnClickListener(this);
        endTime.setOnClickListener(this);
        record.setOnClickListener(this);
        attend.setOnClickListener(this);
        respons.setOnClickListener(this);
        commitBtn.setOnClickListener(this);
        isMessage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                Toast.makeText(BaseApplication.getContext(), "暂不支持短信", Toast.LENGTH_LONG).show();
                isMessage.setChecked(false);
            }
        });
    }

    //初始化地址下滑
    private void initAddSpinner() {
        // 建立Adapter并且绑定数据源
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, hysList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //绑定 Adapter到控件
        spinnerAddress .setAdapter(adapter);
        //添加事件Spinner事件监听

        spinnerAddress.setOnItemSelectedListener(new SpinnerAddressListener());
    }
    //初始化部门下滑菜单
    private void initDeptSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, deptList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerDept .setAdapter(adapter);

        spinnerDept.setOnItemSelectedListener(new SpinnerDeptListener());
    }



    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id==android.R.id.home){
            this.finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_startTime:
                pwStartTime.setCyclic(true);
                pwStartTime.showAtLocation(startTime, Gravity.BOTTOM, 0, 0, new Date());
                break;
            case R.id.tv_endTime:
                pwEndTime.setCyclic(true);
                pwEndTime.showAtLocation(endTime, Gravity.BOTTOM, 0, 0, new Date());
                break;
            case R.id.tv_record:
                Intent intent=new Intent(MyConferenceUpdateActivity.this,TreeActivity.class);
                intent.putExtra("TREELIST",(Serializable) treeInfoList);
                startActivityForResult(intent,1);
                break;
            case R.id.tv_respons:
                Intent intent2=new Intent(MyConferenceUpdateActivity.this,TreeActivity.class);
                intent2.putExtra("TREELIST", (Serializable) treeInfoList);
                startActivityForResult(intent2,2);
                break;
            case R.id.tv_attend:
                Intent intent3=new Intent(MyConferenceUpdateActivity.this,TreeActivity.class);
                intent3.putExtra("TREELIST", (Serializable) treeInfoList);
                startActivityForResult(intent3,3);
                break;
            case R.id.bt_submit:
                AlertDialog.Builder builder=new AlertDialog.Builder(this);
                builder.setTitle("提交")
                        .setMessage("确认提交吗")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //我组织的会议修改事件
                                //提交数据
                                boolean isAll=isEmpty();
                                if (isAll){
                                    //如果正确开始访问网络
                                    AddUpdateImpl addUpdateImpl=new AddUpdateImpl(new AddHttpResultListener());
                                    addUpdateImpl.addUpdate(account, hysId, recordId, recordId, attendId, stime, etime, hydd,
                                            subject.getText().toString(), discribe.getText().toString(),
                                            deptName, prepare.getText().toString(),comeetingInfo.getId(), "");
                                }else {
                                    ToastUtil.showToast(MyConferenceUpdateActivity.this, "请确保填写完整");
                                }
                            }
                        })
                        .setNegativeButton("取消",new DialogInterface.OnClickListener(){
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                dialogInterface.dismiss();
                            }
                        }).show();
                break;
        }
    }

    class AddHttpResultListener implements HttpResultListener{

        @Override
        public void onStartRequest() {
            showDialog.Loading("正在修改...");
        }

        @Override
        public void onResult(Object obj) {
            if (obj instanceof FailRequest) {
                showDialog.dismissDialog();
                if (!((FailRequest) obj).getStatus().equals(0)) {
                    ToastUtil.showToast(MyConferenceUpdateActivity.this, ((FailRequest) obj).getMsg());
                }
            } else {
                //成功
//                Intent intent=getIntent();
//                ComeetingInfo comeetingInfo=new ComeetingInfo();
//                comeetingInfo.setHyzt(subject.getText().toString());
//                comeetingInfo.setHysmc(hydd);
//                comeetingInfo.setHydd(destination.getText().toString());
//                comeetingInfo.setFzr(responsName);
//                comeetingInfo.setJlr(recordName);
//                comeetingInfo.setChry(attendName);
//                comeetingInfo.setSqr(account);
//                comeetingInfo.setEtime(etime);
//                comeetingInfo.setStime(stime);
//                comeetingInfo.setStatus("1");
//                comeetingInfo.setChryid(attendId);
//                comeetingInfo.setFzrid(responsId);
//                comeetingInfo.setJlrid(recordId);
//                comeetingInfo.setHyms(discribe.getText().toString());
//                comeetingInfo.setMessage("2");
//                comeetingInfo.setId("");
//                comeetingInfo.setCreateat("");
//                comeetingInfo.setOrgid("");
//                comeetingInfo.setUseflag("");
//                Bundle bundle =new Bundle();
//                bundle.putSerializable("cometinfo",comeetingInfo);
//                intent.putExtras(bundle);
//                showDialog.dismissDialog();
//                setResult(0, intent);
                MyConferenceUpdateActivity.this.finish();
            }
        }

        @Override
        public void onFinish() {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data!=null){
            switch (requestCode){
                case 1:
                    //记录人员
                    recordId=data.getStringExtra("id");
                    recordName=data.getStringExtra("name");
                    record.setText(recordName);
                    break;
                case 2:
                    //负责人员
                    responsId=data.getStringExtra("id");
                    responsName=data.getStringExtra("name");
                        respons.setText(responsName);
                    break;
                case 3:
                    //参会人员
                    attendId=data.getStringExtra("id");
                    attendName=data.getStringExtra("name");
                    attend.setText(attendName);
                    break;
            }
        }
    }

    //spinner点击事件
    class SpinnerAddressListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
                                   long l) {
//            if (hysList.size()==1){
//                hysInfoList.get(0).getName();
//                destination.setText(hysInfoList.get(0).getName());
//            }else {
            destination.setText(hysInfoList.get(position).getName());
            hydd=destination.getText().toString();
            hysId=hysInfoList.get(position).getId();
            // }

        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    }
    //spinner点击事件
    class SpinnerDeptListener implements AdapterView.OnItemSelectedListener {

        public void onItemSelected(AdapterView<?> arg0, View arg1, int i,
                                   long l) {
            deptName=deptInfoList.get(i).getName();
        }

        public void onNothingSelected(AdapterView<?> arg0) {

        }
    }

    //日期转换成字符串
    public static String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }

    //日期转换成毫秒值
    public static long getMillisTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String choseTime = format.format(date);
        try {
            return format.parse(choseTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }
    //日期类型的字符串转换成毫秒值
    public static long getMillisTime(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        try {
            return format.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public boolean isEmpty(){
        if (!TextUtils.isEmpty(subject.getText().toString())&& !TextUtils.isEmpty(prepare.getText().toString())&& !TextUtils.isEmpty(discribe.getText().toString())
                &&!recordName.equals("")&& !responsName.equals("")&& !attendName.equals("")&&!TextUtils.isEmpty(endTime.getText().toString())&&
                !TextUtils.isEmpty(startTime.getText().toString()))
        {
            return true;
        }else {
            return false;
        }

    }

}
